import React, { Component, useRef } from 'react'
import { SearchOutlined } from "@ant-design/icons";
import { Input, Space, Form, Button } from 'antd'
import _ from 'lodash'
import { phoneReg } from '@/utils/regexp'
import { apiGetSalesmanPage, apiGetSalesmanAdd, apiGetSalesmanEdit, apiGetSalesmanDel, apiGetSalesmanMonthList, apiGetSalesmanDayList } from '@/request/salesman'
import TheButton from '@/components/TheButton'
import ThePagination from '@/components/ThePagination'
import TheTable from '@/components/TheTable'
import TheDialog from '@/components/TheDialog'

const SearchHeader = ({ getValue, openAdd }) => {
  const formRef = useRef()
  const onFinish = (values) => {
    _.forIn(values, (v, k) => {
      if (!v) {
        delete (values[k])
      }
    })
    getValue(values)
  }
  const reset = () => {
    formRef.current.setFieldsValue({
      shoppingGuideName: ''
    })
    getValue({})
  }
  return <div style={{ display: 'flex', justifyContent: 'space-between' }}>
    <Form layout={'inline'} onFinish={onFinish} ref={formRef}>
      <Form.Item name='shoppingGuideName'>
        <Input suffix={<SearchOutlined />} placeholder="导购员姓名" />
      </Form.Item>
      <Form.Item>
        <Space>
          <Button type='primary' htmlType='submit'>搜索</Button>
          <Button onClick={reset}>重置</Button>
        </Space>
      </Form.Item>
    </Form>
    <TheButton hasPermi={['cashier:salesman:add']} onClick={openAdd} size="middle" type='default'>新增导购员</TheButton>
  </div>
}

export default class Salesman extends Component {
  state = {
    pageData: {
      pageNo: 1,
      pageSize: 10
    },
    total: 0,
    searchValue: {},
    columns: [
      {
        title: '导购员姓名',
        dataIndex: 'shoppingGuideName',
        key: 'shoppingGuideName'
      },
      {
        title: '联系电话',
        dataIndex: 'shoppingGuideMobile',
        key: 'shoppingGuideMobile'
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime'
      },
      {
        title: '操作',
        render: (text, record) => {
          return <>
            <TheButton  hasPermi={['cashier:salesman:amount']}  onClick={() => this.openMonthDialog(record)}>提成金额</TheButton>
            <TheButton  hasPermi={['cashier:salesman:edit']}  onClick={() => this.updateSalesman(record)}>编辑</TheButton>
            <TheButton  hasPermi={['cashier:salesman:delete']}  onClick={() => this.delConfirm(record)}>删除</TheButton>
          </>
        }
      }
    ],
    dataSource: [],
    loading: false,
    shoppingGuideId: '',
    editValue: {},
    monthVisible: false,
    monthData: [],
    monthColumns: [
      {
        title: '月份',
        dataIndex: 'shoppingGuideMonth',
        key: 'shoppingGuideMonth'
      },
      {
        title: '提成总金额',
        dataIndex: 'shoppingGuideMonthPrice',
        key: 'shoppingGuideMonthPrice',
        render: (text, record) => {
          return <React.$Price price={text || 0} />
        }
      },
      {
        title: '操作',
        render: (text, record) => {
          return <TheButton onClick={() => this.openDayDialog(record)}>查看当月详情</TheButton>
        }
      }
    ],
    dayVisible: false,
    dayData: [],
    dayColumns: [
      {
        title: '日期',
        dataIndex: 'shoppingGuideDay',
        key: 'shoppingGuideDay'
      },
      {
        title: '提成金额',
        dataIndex: 'shoppingGuideDayPrice',
        key: 'shoppingGuideDayPrice',
        render: (text, record) => {
          return <React.$Price price={text || 0} />
        }
      }
    ],
    monthLoading: false,
    dayLoading: false
  }

  componentDidMount() {
    this.getData()
  }

  getData = async () => {
    this.setState({ loading: true })
    const { pageData, searchValue } = this.state
    let res = await apiGetSalesmanPage({ ...pageData, ...searchValue })
    if (res.data && res.code === 0) {
      this.setState({
        dataSource: res.data,
        pageData: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        total: res.totalCount
      })
    }
    this.setState({ loading: false })
  }

  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })
  };

  getValue = value => {
    this.setState({
      searchValue: value,
      pageData: {
        pageNo: 1,
        pageSize: 10
      }
    }, () => this.getData())
  }

  openAdd = () => {
    this.setState({
      visible: true,
      title: '新增导购员',
      shoppingGuideId: ''
    })
  }

  updateSalesman = (value) => {
    const { shoppingGuideId, shoppingGuideMobile, shoppingGuideName } = value
    this.setState({
      visible: true,
      title: '修改导购员',
      shoppingGuideId,
      editValue: {
        shoppingGuideMobile,
        shoppingGuideName
      }
    })
  }

  handleCancel = () => {
    this.setState({
      visible: false,
      title: '',
      shoppingGuideId: '',
      editValue: {}
    })
  }

  delConfirm = (value) => {
    const { shoppingGuideId } = value
    React.$confirm({
      title: '您确认删除此导购员信息吗？',
      onOk: async () => {
        let res = await apiGetSalesmanDel({ shoppingGuideId })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '删除成功'
          })
          this.getData()
        }
      }
    })
  }

  editSalesman = async (value) => {
    const { shoppingGuideId } = this.state
    this.setState({ btnLoading: true })
    if (shoppingGuideId) {
      let res = await apiGetSalesmanEdit({ ...value, shoppingGuideId })
      if (res.code === 0) {
        React.$message({
          type: 'info',
          content: '修改成功'
        })
      }
    } else {
      let res = await apiGetSalesmanAdd({ ...value })
      if (res.code === 0) {
        React.$message({
          type: 'info',
          content: '新增成功'
        })
      }
    }
    this.setState({ btnLoading: false })
    this.handleCancel()
    this.getData()
  }

  openMonthDialog = async value => {
    const { shoppingGuideId } = value
    this.setState({
      monthVisible: true,
      monthLoading: true,
      shoppingGuideId
    })
    let res = await apiGetSalesmanMonthList({ shoppingGuideId })
    if (res.data && res.code === 0) {
      this.setState({
        monthData: res.data,
      })
    }
    this.setState({
      monthLoading: false
    })
  }

  monthClose = () => {
    this.setState({
      monthVisible: false
    })
  }

  openDayDialog = async value => {
    const { shoppingGuideId } = this.state
    const { shoppingGuideMonth } = value
    let res = await apiGetSalesmanDayList({ shoppingGuideId, month: shoppingGuideMonth })
    if (res.data && res.code === 0)
      this.setState({
        monthVisible: false,
        dayVisible: true,
        dayData: res.data
      })
  }

  dayDialogClose = () => {
    this.setState({
      monthVisible: true,
      dayVisible: false
    })
  }

  render() {
    const { columns, dataSource, loading, pageData: { pageNo, pageSize }, total, visible, title, btnLoading, editValue, monthVisible, monthColumns, monthData, dayVisible, dayData, dayColumns, monthLoading, dayLoading } = this.state
    return (
      <div className='p-layout-box'>
        <SearchHeader getValue={this.getValue} openAdd={this.openAdd} />
        <div className="p-layout-content-pagination">
          <TheTable columns={columns} dataSource={dataSource} loading={loading} scroll={{ x: "max-content", y: '63vh' }} />
          <ThePagination pageNo={pageNo} pageSize={pageSize} total={total} pageChange={this.pageChange} />
        </div>
        <TheDialog
          width={400}
          visible={visible}
          title={title}
          footer={null}
          handleCancel={this.handleCancel}
        >
          <Form initialValues={editValue} onFinish={this.editSalesman} labelCol={{ span: 9 }} labelAlign="left">
            <Form.Item label="导购员姓名" name='shoppingGuideName' rules={[{ required: true }]}>
              <Input />
            </Form.Item>
            <Form.Item label="导购员联系方式" name='shoppingGuideMobile' rules={[{ required: true }, { pattern: phoneReg, message: '请输入正确手机号码' }]}>
              <Input />
            </Form.Item>
            <Form.Item>
              <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: -30 }}>
                <Space align="end">
                  <Button onClick={this.handleCancel}>取消</Button>
                  <Button type='primary' htmlType='submit' loading={btnLoading}>确认</Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </TheDialog>
        <TheDialog
          width={600}
          visible={monthVisible}
          title={'提成金额'}
          footer={
            <div>
              <Button type='primary' onClick={this.monthClose}>确认</Button>
            </div>
          }
          handleCancel={this.monthClose}
        >
          <TheTable loading={monthLoading} columns={monthColumns} dataSource={monthData} />
        </TheDialog>
        <TheDialog
          width={400}
          visible={dayVisible}
          title={'提成金额'}
          footer={
            <div>
              <Button type='primary' onClick={this.dayDialogClose}>确认</Button>
            </div>
          }
          handleCancel={this.dayDialogClose}
        >
          <TheTable columns={dayColumns} dataSource={dayData} />
        </TheDialog>
      </div >
    )
  }
}
